package org.rslai.util.md5;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * MD5计算工具
 * 
 * @author rslai
 */
public class MD5 {
	private static MD5 instance = new MD5();

	/**
	 * 返回一个 MD5 实例
	 * @return MD5 实例
	 */
	public static MD5 getInstance() {
		return instance;
	}

	/**
	 * 私有化构造函数
	 */
	private MD5() {
		
	}

	/**
	 * 返回指定文件的 MD5 码
	 * @param fileName 文件名+路径
	 * @return MD5 码
	 * @throws Exception
	 */
	public String getMd5ByFile(String fileName) throws Exception {
		String value = null;
		FileInputStream in = null;
		try {
			File file = new File(fileName);
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			throw e;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}

}
